import base64
import json

import pickle

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU


class CartsView(View):
    def get(self, request):
        # 1.接收数据
        user = request.user

        # 2.检验数据

        # 3.处理业务
        if user.is_authenticated:
            # 判断cookie是否有购物车
            cart_bytes = request.COOKIES.get('carts')
            if cart_bytes:
                cart_dict = pickle.loads(base64.b64decode(cart_bytes))
                redis_client = get_redis_connection('carts')

                for sku_id, count_selected in cart_dict.items():
                    redis_client.hset('cart_%s' % user.id, sku_id, count_selected['count'])
                    if count_selected['selected']:  # 是bool值
                        redis_client.sadd('selected_%s' % user.id, sku_id)
                    else:
                        redis_client.srem('selected_%s' % user.id, sku_id)

            redis_conn = get_redis_connection('carts')
            cart_redis = redis_conn.hgetall('cart_%s' % user.id)
            selected_redis = redis_conn.smembers('selected_%s' % user.id)
            sku_list = []
            for sku_id, count in cart_redis.items():
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id': sku.id,
                    'name': sku.name,
                    'price': float(sku.price),
                    'default_image_url': sku.default_image_url.url,
                    'count': int(count),
                    'amount': float(sku.price * int(count)),
                    'selected': str(sku_id in selected_redis)
                }
                sku_list.append(sku_data)

            # 4.返回响应
            context = {
                'cart_skus': sku_list
            }
            response = render(request, 'cart.html', context=context)
            response.delete_cookie('carts')
            return response
        else:
            cart_b64 = request.COOKIES.get('carts')
            if cart_b64:
                # base64 -> bytes
                cart_bytes = base64.b64decode(cart_b64)
                # bytes -> dict
                cart_dict = pickle.loads(cart_bytes)
            else:
                cart_dict = {}
            # 便利购物车,构造数据
            sku_list = []
            for sku_id in cart_dict:
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id': sku.id,
                    'name': sku.name,
                    'price': float(sku.price),
                    'default_image_url': sku.default_image_url.url,
                    'count': int(cart_dict[sku_id]['count']),
                    'amount': float(sku.price * int(cart_dict[sku_id]['count'])),
                    'selected': str(cart_dict[sku_id]['selected'])
                }
                sku_list.append(sku_data)
            context = {
                'cart_skus': sku_list
            }
            return render(request, 'cart.html', context=context)

    def post(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        if not all([sku_id, count]):
            return JsonResponse({'code': 9999, 'errmsg': '数据不全'})
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return JsonResponse({'code': 9999, 'errmsg': '商品id不存在'})
        if int(count) < 1:
            return JsonResponse({'code': 9999, 'errmsg': '商品数量不能少于1'})

        user = request.user

        if user.is_authenticated:
            redis_client = get_redis_connection('carts')
            redis_client.hincrby('cart_%s' % user.id, sku_id, count)
            redis_client.sadd('selected_%s' % user.id, sku_id)
            res = {
                'code': 0,
                'errmsg': '成功',
                'sku_count': count
            }
            return JsonResponse(res)
        else:
            carts_b64 = request.COOKIES.get('carts')
            if carts_b64:
                carts_b64 = base64.b64decode(carts_b64)
                carts_dict = pickle.loads(carts_b64)
            else:
                carts_dict = {}

            if sku_id in carts_dict:
                carts_dict[sku_id]['count'] += count
            else:
                carts_dict[sku_id] = {
                    'count': count,
                    'selected': True
                }

            cart_dict_byte = pickle.dumps(carts_dict)
            cart_b64 = base64.b64encode(cart_dict_byte)
            res = {
                'code': 0,
                'errmsg': '成功',
                'sku_count': count
            }

            response = JsonResponse(res)
            response.set_cookie('carts', cart_b64, expires=3600 * 24 * 14)
            return response

    def put(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected')
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '商品id不正确'})
        try:
            count = int(count)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '数量格式不正确'})
        if count < 1:
            return JsonResponse({'code': 9999, 'errmsg': '数量不正确'})

        user = request.user
        if user.is_authenticated:
            # 登陆用户
            # 从redis获取数据
            redis_conn = get_redis_connection('carts')
            # 新数据覆盖到购物车
            redis_conn.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                redis_conn.sadd('selected_%s' % user.id, sku_id)
            else:
                redis_conn.srem('selected_%s' % user.id, sku_id)
            res = {
                'code': 0,
                'errmsg': '成功',
                'cart_sku': {
                    'selected': selected,
                    'count': count
                }
            }
            return JsonResponse(res)
        else:
            # 非登陆用户
            # 1.从cookie获取购物车
            carts_b64 = request.COOKIES.get('carts')
            if carts_b64:
                cart_dict = pickle.loads(base64.b64decode(carts_b64))
            else:
                cart_dict = {}
            # 2.把新数据设置到购物车
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 3.保存到cookie

            cart_b64 = base64.b64encode(pickle.dumps(cart_dict))
            res = {
                'code': 0,
                'errmsg': '成功',
                'cart_sku': {
                    'selected': selected,
                    'count': count,
                }
            }
            response = JsonResponse(res)
            response.set_cookie('carts', cart_b64, 3600 * 24 * 7)
            return response

    def delete(self, request):
        # 1.接收数据
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        user = request.user
        # 2.检验数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code': 9999, 'errmsg': '商品id不存在'})
        # 3.处理业务
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_conn.hdel('cart_%s' % user.id, sku_id)
            redis_conn.srem('selected_%s' % user.id, sku_id)
            res = {
                'code': 0,
                'errmsg': '成功',
            }
            return JsonResponse(res)
        else:
            cart_bytes = request.COOKIES.get('carts')
            if cart_bytes:
                cart_dict = pickle.loads(base64.b64decode(cart_bytes))
                # 删除cart_dict中的sku_id的数据
                cart_dict.pop(sku_id)
            else:
                cart_dict = {}
            cart_base64 = base64.b64encode(pickle.dumps(cart_dict))
            # 返回数据
            res = {
                'code': 0,
                'errmsg': '成功'
            }
            response = JsonResponse(res)
            response.set_cookie('carts', cart_base64, expires=3600 * 24 * 14)

            return response


class CartsSelectionView(View):
    def put(self, request):
        # 全选/不全选购物车
        # 1, 接收数据
        data = json.loads(request.body.decode())
        selected = data.get('selected')
        # 2, 校验数据
        pass
        # 3, 处理业务
        user = request.user

        if user.is_authenticated:
            # 登录
            redis_client = get_redis_connection('carts')
            cart_redis_sku_ids = redis_client.hkeys('cart_%s' % user.id)

            # 根据选中状态, 设置  redis中的数据
            if selected:
                redis_client.sadd('selected_%s' % user.id, *cart_redis_sku_ids)
            else:
                redis_client.srem('selected_%s' % user.id, *cart_redis_sku_ids)

            res = {
                'code': 0,
                'errmsg': '成功'
            }
            return JsonResponse(res)
            pass
        else:
            # 非登录
            cart_bytes = request.COOKIES.get('carts')
            if cart_bytes:
                cart_dict = pickle.loads(base64.b64decode(cart_bytes))
                # {
                #     sku_id:{
                #         'count':3,
                #         'selected':True
                #     },
                #     sku_id: {
                #         'count': 3,
                #         'selected': True
                #     }
                # }

                for sku_id, value in cart_dict.items():
                    value['selected'] = selected


            else:
                cart_dict = {}

            # dict -> base64
            # 4, 返回响应

            cart_base64 = base64.b64encode(pickle.dumps(cart_dict))

            res = {
                'code': 0,
                'errmsg': '成功',
            }

            response = JsonResponse(res)
            response.set_cookie('carts', cart_base64, expires=3600 * 24 * 14)

            return response


class CartsSimpleView(View):
    def get(self, request):
        # 1.接收数据
        user = request.user
        # 2.检验数据
        pass
        # 3.处理业务
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart_dict = redis_conn.hgetall('cart_%s' % user.id)
            cart_skus = []
            for sku_id, count in cart_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id': sku.id,
                    'image': sku.default_image_url.url,
                    'name': sku.name,
                    'count': int(count)
                }
                cart_skus.append(sku_data)
        else:
            base64_data = request.COOKIES.get('carts')
            if base64_data:
                cart_dict = pickle.loads(base64.b64decode(base64_data))
            else:
                cart_dict = {}
            cart_skus = []
            for sku_id, data in cart_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id': sku.id,
                    'image': sku.default_image_url.url,
                    'name': sku.name,
                    'count': data['count']
                }
                cart_skus.append(sku_data)
        # 4.返回响应
        res = {
            'code': 0,
            'cart_skus': cart_skus,
            'errmsg': '成功'
        }
        return JsonResponse(res)
